//
//  MeViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "MeViewController.h"
#import "SettingViewController.h"
#import "GatewayManageController.h"
#import "GatewaySharedController.h"
#import "MeRoomManageController.h"
#import "MyDeviceManageController.h"
#import "MeInfoViewController.h"
#import "AboutViewController.h"
#import "NewDeviceViewController.h"
#import "MeHeaderView.h"
#import "MeModelGroup.h"
#import "PushConfigModel.h"
#import "MQTTSessionManager.h"
#import "UIView+Frame.h"
#import "CommonUtils.h"
#import "Friend.h"

static NSString *const kZTMeViewTableViewreuseIdentifier = @"kZTMeViewTableViewreuseIdentifier";

@interface MeViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
MeHeaderViewDelegate,
DataManagerRefreshDelegate
>
NS_ASSUME_NONNULL_BEGIN
@property (nonatomic, strong) MeHeaderView *headerView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray <MeModelGroup *>*datas;
@property (nonatomic, weak)   UITableViewCell *securityCell;
NS_ASSUME_NONNULL_END
@property (nullable, nonatomic, strong) UIView* guideView;
@property (nonatomic, assign) BOOL guideFlag;
@end

@implementation MeViewController


#pragma mark - life cycle

- (void)dealloc
{
    [kDataManager removeNewJoinRefreshDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [kDataManager addNewJoinRefreshDelegate:self];
    [kDataManager addFriendRefreshDelegate:self];
    [self newJoinRefresh:kDataManager];
    [self friendRefresh:kDataManager callbackType:FriendCallbackTypeName];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.headerView.strPhone = kMQTTSessionManager.currentUser.m_strTel;
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self setupFirstGuide];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - event response

- (void)guideImgTapped {
    if(self.guideFlag) {
        self.guideFlag = NO;
        [UIView animateWithDuration:0.5 animations:^{
            [self.guideView removeFromSuperview];
            self.guideView = nil;
        } completion:^(BOOL finished) {
            [self addNewDeviceGuideView];
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            [self.guideView removeFromSuperview];
            self.guideView = nil;
        }];
    }
}

#pragma mark - DataManagerRefreshDelegate
- (void)newJoinRefresh:(DataManager* __nonnull)manager
{
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
    });
}

- (void)friendRefresh:(DataManager *)manager callbackType:(FriendCallbackType)callbackType {
    if (callbackType == FriendCallbackTypeName) {
        Friend* friend = [kDataManager fetchFriendWithApsn:kMQTTSessionManager.currentUser.apsn luid:kMQTTSessionManager.currentUser.luid];
        if (friend) {
            self.headerView.name = friend.name;
        } else {
            self.headerView.name = nil;
        }
    }
}


#pragma mark - MeHeaderViewDelegate
- (void)meHeaderViewDidClick:(MeHeaderViewClickType)clickType
{
    switch (clickType) {
        case MeHeaderViewClickTypeSetting:
        {
            SettingViewController *settingVc = [SettingViewController createSettingController];
            [self.navigationController pushViewController:settingVc animated:YES];
        }
            break;
        case MeHeaderViewClickTypeIcon:
        {
            MeInfoViewController *meInfoVc = [[MeInfoViewController alloc]init];
            [self.navigationController pushViewController:meInfoVc animated:YES];
        }
            break;
        case MeHeaderViewClickTypeBack:
            [self.navigationController popViewControllerAnimated:YES];
            break;
        default:
            break;
    }
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas[section].groups.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kZTMeViewTableViewreuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kZTMeViewTableViewreuseIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    MeModel *model = self.datas[indexPath.section].groups[indexPath.row];
    cell.textLabel.text = model.title;
    cell.imageView.image = [UIImage imageNamed:model.icon];
    if (indexPath.section == 0 && indexPath.row== self.datas[indexPath.section].groups.count - 1)
    {
        if (kDataManager.joinDevListenList.count > 0)
        {
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundColor:RGBColor(153,153,153)];
            button.frame = CGRectMake(0, 0, 30, 30);
            button.layer.cornerRadius = button.frame.size.width * 0.5;
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            NSString* title = [NSString stringWithFormat:@"%zd",kDataManager.joinDevListenList.count];
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            cell.accessoryView = button;
        }
        else
        {
            cell.accessoryView = nil;
        }
    }
    return cell;
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        GatewayManageController *gatewayManageVc = [[GatewayManageController alloc]init];
        [self.navigationController pushViewController:gatewayManageVc animated:YES];
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        MyDeviceManageController *myDevManageVc= [[MyDeviceManageController alloc]init];
        [self.navigationController pushViewController:myDevManageVc animated:YES];
    }
    else if (indexPath.section == 0 && indexPath.row == 2) {
        MeRoomManageController *meRoomManageVc = [[MeRoomManageController alloc]init];
        [self.navigationController pushViewController:meRoomManageVc animated:YES];
    }
    else if (indexPath.section == 0 && indexPath.row == 3) {
        NewDeviceViewController* newDeviceVc = [[NewDeviceViewController alloc]init];
        [self.navigationController pushViewController:newDeviceVc animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 0) {
        GatewaySharedController *gatewayVc= [[GatewaySharedController alloc]init];
        [self.navigationController pushViewController:gatewayVc animated:YES];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        AboutViewController *aboutVc = [[AboutViewController alloc]init];
        [self.navigationController pushViewController:aboutVc animated:YES];
    }
}

#pragma mark - private method
- (void)setupFirstGuide {
    if([CommonUtils isNewUpdateWithKey:@"firstLaunchGuide"])
    {
        //第一次启动
        self.guideFlag = YES;
        [self addGatewayGuideView];
    } else  {
        //不是第一次启动了
    }
}
- (void)addGatewayGuideView {
    NSIndexPath* idx = [NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:idx];
    if (!cell) {
        return;
    }
    UIImage* img = [self viewCoverToImage:cell];
    [[UIApplication sharedApplication].keyWindow addSubview:self.guideView];
    [self.guideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo([UIApplication sharedApplication].keyWindow);
    }];
    
    UIView* guideBackgroundView = [[UIView alloc]init];
    guideBackgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    [self.guideView addSubview:guideBackgroundView];
    [guideBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.guideView);
    }];
    UIImageView* gatewayGuideView = [[UIImageView alloc]init];
    gatewayGuideView.backgroundColor = [UIColor whiteColor];
    gatewayGuideView.image = img;
    [guideBackgroundView addSubview:gatewayGuideView];
    CGRect rect = [cell convertRect:cell.bounds toView:guideBackgroundView];
    gatewayGuideView.frame = rect;
    UIImageView* guideImg  = [[UIImageView alloc]init];
    guideImg.image = [UIImage imageNamed:@"me_guide_gateway"];
    guideImg.userInteractionEnabled = YES;
    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(guideImgTapped)];
    [guideImg addGestureRecognizer:tapGesture];
    [guideBackgroundView addSubview:guideImg];
    [guideImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(gatewayGuideView.bottom);
        make.centerX.equalTo(gatewayGuideView);
        make.width.equalTo(kIphoneSize_Widith(271));
        make.height.equalTo(kIphoneSize_Height(192));
    } ];
}


- (void)addNewDeviceGuideView {
    NSIndexPath* idx = [NSIndexPath indexPathForRow:3 inSection:0];
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:idx];
    if (!cell) {
        return;
    }
    UIImage* img = [self viewCoverToImage:cell];
    [[UIApplication sharedApplication].keyWindow addSubview:self.guideView];
    [self.guideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo([UIApplication sharedApplication].keyWindow);
    }];
    
    UIView* guideBackgroundView = [[UIView alloc]init];
    guideBackgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    [self.guideView addSubview:guideBackgroundView];
    [guideBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.guideView);
    }];
    UIImageView* gatewayGuideView = [[UIImageView alloc]init];
    gatewayGuideView.backgroundColor = [UIColor whiteColor];
    gatewayGuideView.image = img;
    [guideBackgroundView addSubview:gatewayGuideView];
    CGRect rect = [cell convertRect:cell.bounds toView:guideBackgroundView];
    gatewayGuideView.frame = rect;
    UIImageView* guideImg  = [[UIImageView alloc]init];
    guideImg.image = [UIImage imageNamed:@"me_guide_newdevice"];
    guideImg.userInteractionEnabled = YES;
    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(guideImgTapped)];
    [guideImg addGestureRecognizer:tapGesture];
    [guideBackgroundView addSubview:guideImg];
    
    [guideImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(gatewayGuideView.top);
        make.centerX.equalTo(gatewayGuideView);
        make.width.equalTo(kIphoneSize_Widith(218));
        make.height.equalTo(kIphoneSize_Height(201));
    } ];
}

- (void)initSubviews {
    self.headerView.yh_height = 228.f;
    self.headerView.delegate = self;
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (UIImage*)viewCoverToImage:(UIView*)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, [UIScreen mainScreen].scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

#pragma mark - getters and setters

- (MeHeaderView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[MeHeaderView alloc]init];
    }
    return _headerView;
}
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator= NO;
        _tableView.rowHeight = kIphoneSize_Height(52);
        _tableView.sectionFooterHeight = 0;
        UIView *footerView = [[UIView alloc]init];
        _tableView.tableFooterView = footerView;
    }
    return _tableView;
}

- (NSArray<MeModelGroup *> *)datas
{
    if (!_datas) {
        _datas = [MeModelGroup loadData];
    }
    return _datas;
}

- (UIView *)guideView
{
    if (!_guideView) {
        _guideView = [[UIView alloc]init];
    }
    return _guideView;
}

@end
